// src/stores/permission.js
import { defineStore } from 'pinia';
import router from '@/router'; // 导入路由实例

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: [], // 最终路由表
    addRoutes: [] // 动态添加的路由
  }),
  actions: {
    /**
     * 生成动态路由并添加到路由实例
     * @param {Array} menuList - 后端返回的菜单列表
     */
    async generateRoutes(menuList) {
      // 将菜单数据转换为路由配置
      const accessedRoutes = this.transformMenuToRoutes(menuList);

      // 保存路由配置
      // this.addRoutes = accessedRoutes;
      this.routes = [...router.getRoutes(), ...accessedRoutes];
      console.log('==========1===menuList====>', router.getRoutes());

      // 动态添加路由
      accessedRoutes.forEach(route => {
        router.addRoute(route);
      });
      addRoute()

      return accessedRoutes;
    },

    /**
     * 将菜单数据转换为路由配置
     * @param {Array} menuList - 菜单列表
     */
    transformMenuToRoutes(menuList) {
      return menuList.map(menu => {
        const route = {
          path: menu.path,
          name: menu.name,
          component: () => import(`@/views/${menu.component}.vue`), // 动态导入组件
          meta: menu.meta
        };

        // 处理子路由
        if (menu.children && menu.children.length > 0) {
          route.children = this.transformMenuToRoutes(menu.children);
        }

        return route;
      });
    }
  }
});
